<template>
  <div class="course-detail" @contextmenu.prevent="handleContextMenu">
    <div class="video-section">
      <div class="video-player">
        <video
          ref="videoPlayer"
          class="video-js"
          controls
          preload="auto"
          width="100%"
          height="500"
        >
          <source :src="currentVideo.url" type="video/mp4">
        </video>
      </div>
      <div class="video-info">
        <h2>{{ currentVideo.title }}</h2>
        <p>{{ currentVideo.description }}</p>
        <div class="video-meta">
          <span><el-icon><Clock /></el-icon> {{ currentVideo.duration }}</span>
          <span><el-icon><View /></el-icon> {{ currentVideo.views }}次观看</span>
        </div>
      </div>

      <div class="notes-section">
        <div class="notes-header">
          <h3>学习笔记</h3>
          <div class="notes-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索笔记..."
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="selectedCategory" placeholder="选择分类" clearable>
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
            <el-button type="primary" @click="showAddNoteDialog">
              <el-icon><Plus /></el-icon> 添加笔记
            </el-button>
            <el-button @click="exportNotes">
              <el-icon><Download /></el-icon> 导出笔记
            </el-button>
          </div>
        </div>

        <div class="notes-list">
          <div v-for="note in filteredNotes" :key="note.id" class="note-item">
            <div class="note-header">
              <div class="note-info">
                <span class="note-time">{{ formatTime(note.createTime) }}</span>
                <el-tag size="small" :type="getCategoryTagType(note.categoryId)">
                  {{ getCategoryName(note.categoryId) }}
                </el-tag>
              </div>
              <div class="note-actions">
                <el-button type="text" @click="editNote(note)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="text" @click="deleteNote(note)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <div class="note-content" v-html="note.content"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="practice-section">
      <h3>练习题</h3>
      <div v-if="currentQuestion" class="question-card">
        <div class="question-content">
          <h4>{{ currentQuestion.title }}</h4>
          <p>{{ currentQuestion.description }}</p>

          <template v-if="currentQuestion.type === 'choice'">
            <el-radio-group v-model="selectedAnswer">
              <el-radio
                v-for="option in currentQuestion.options"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </template>

          <template v-if="currentQuestion.type === 'code'">
            <div class="code-editor">
              <el-input
                v-model="codeAnswer"
                type="textarea"
                :rows="6"
                placeholder="请输入你的代码..."
              />
              <div class="code-actions">
                <el-button type="primary" @click="runCode">运行代码</el-button>
                <el-button @click="showTestCases">查看测试用例</el-button>
              </div>
              <div v-if="codeOutput" class="code-output">
                <h4>运行结果：</h4>
                <pre>{{ codeOutput }}</pre>
              </div>
              <div v-if="testResults.length" class="test-results">
                <h4>测试用例结果：</h4>
                <div v-for="(result, index) in testResults" :key="index"
                     :class="['test-case', result.passed ? 'passed' : 'failed']">
                  <div class="test-header">
                    <span>测试用例 {{ index + 1 }}</span>
                    <el-tag :type="result.passed ? 'success' : 'danger'">
                      {{ result.passed ? '通过' : '失败' }}
                    </el-tag>
                  </div>
                  <div class="test-details">
                    <p><strong>输入：</strong>{{ result.input }}</p>
                    <p><strong>期望输出：</strong>{{ result.expected }}</p>
                    <p><strong>实际输出：</strong>{{ result.actual }}</p>
                    <p v-if="!result.passed"><strong>错误信息：</strong>{{ result.error }}</p>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>

        <div class="question-actions">
          <el-button @click="previousQuestion" :disabled="currentQuestionIndex === 0">
            上一题
          </el-button>
          <el-button type="primary" @click="submitAnswer">
            {{ isLastQuestion ? '提交' : '下一题' }}
          </el-button>
        </div>
      </div>

      <div v-else class="practice-complete">
        <el-result
          icon="success"
          title="练习完成"
          :sub-title="`得分：${score}分`"
        >
          <template #extra>
            <el-button type="primary" @click="reviewAnswers">查看解析</el-button>
            <el-button @click="retryPractice">重新练习</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </div>

  <!-- 右键菜单 -->
  <div v-if="contextMenuVisible" 
       class="context-menu" 
       :style="{ left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px' }">
    <div class="context-menu-item" @click="handleAIQuestion">
      <el-icon><ChatDotRound /></el-icon>
      <span>AI提问</span>
    </div>
    <div class="context-menu-item" @click="handleSelectedTextQuestion" v-if="selectedText">
      <el-icon><Document /></el-icon>
      <span>询问选中内容</span>
    </div>
  </div>

  <!-- AI聊天组件 -->
  <AIChatDrawer
    v-model="showAIChat"
    :course-id="currentVideo.id"
    :initial-message="selectedText"
  />

  <!-- 笔记编辑对话框 -->
  <el-dialog
    v-model="showNoteDialog"
    :title="currentNote ? '编辑笔记' : '添加笔记'"
    width="70%"
  >
    <el-form>
      <el-form-item label="分类">
        <el-select v-model="noteForm.categoryId" placeholder="选择分类">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="noteForm.content"
          type="textarea"
          :rows="10"
          placeholder="请输入笔记内容..."
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showNoteDialog = false">取消</el-button>
        <el-button type="primary" @click="saveNote">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, shallowRef, onBeforeUnmount, nextTick } from 'vue'
import { Clock, View, Plus, Edit, Delete, Search, Download, ChatDotRound, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
import AIChatDrawer from './AIChatDrawer.vue'

// 模拟视频数据
const currentVideo = ref({
  id: 1,
  title: 'AI基础概念讲解',
  description: '本节课将介绍人工智能的基本概念、发展历史和应用场景。',
  url: 'https://example.com/video.mp4',
  duration: '45:30',
  views: 1234
})

// 模拟练习题数据
const questions = ref([
  {
    id: 1,
    type: 'choice',
    title: '什么是人工智能？',
    description: '请选择最准确的描述：',
    options: [
      { label: 'A. 能够像人类一样思考的机器', value: 'A' },
      { label: 'B. 能够模拟人类智能的计算机系统', value: 'B' },
      { label: 'C. 具有自我意识的机器', value: 'C' },
      { label: 'D. 能够完全替代人类的系统', value: 'D' }
    ],
    correctAnswer: 'B'
  },
  {
    id: 2,
    type: 'code',
    title: '实现简单的神经网络',
    description: '请使用Python实现一个简单的前馈神经网络：',
    correctAnswer: 'import numpy as np\n\nclass NeuralNetwork:\n    def __init__(self):\n        self.weights = np.random.rand(10)\n        self.bias = 0\n\n    def forward(self, x):\n        return np.dot(x, self.weights) + self.bias'
  }
])

const currentQuestionIndex = ref(0)
const selectedAnswer = ref('')
const codeAnswer = ref('')
const score = ref(0)

const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])
const isLastQuestion = computed(() => currentQuestionIndex.value === questions.value.length - 1)

// 代码评判相关
const codeOutput = ref('')
const testResults = ref([])
const showTestCasesDialog = ref(false)

// 模拟测试用例数据
const testCases = {
  2: [ // 对应第二个问题（神经网络实现）的测试用例
    {
      input: 'nn = NeuralNetwork()\nx = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\nprint(nn.forward(x))',
      expected: '一个浮点数结果',
      validate: (output) => {
        const result = parseFloat(output)
        return !isNaN(result)
      }
    },
    {
      input: 'nn = NeuralNetwork()\nx = np.zeros(10)\nprint(nn.forward(x))',
      expected: '0.0',
      validate: (output) => {
        const result = parseFloat(output)
        return Math.abs(result) < 0.0001
      }
    }
  ]
}

const submitAnswer = () => {
  if (currentQuestion.value.type === 'choice') {
    if (selectedAnswer.value === currentQuestion.value.correctAnswer) {
      score.value += 100 / questions.value.length
    }
  } else if (currentQuestion.value.type === 'code') {
    // 这里可以添加代码评判逻辑
    score.value += 100 / questions.value.length
  }

  if (isLastQuestion.value) {
    currentQuestion.value = null
  } else {
    currentQuestionIndex.value++
    selectedAnswer.value = ''
    codeAnswer.value = ''
  }
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const reviewAnswers = () => {
  // 实现查看答案解析的逻辑
}

const retryPractice = () => {
  currentQuestionIndex.value = 0
  selectedAnswer.value = ''
  codeAnswer.value = ''
  score.value = 0
}

const runCode = async () => {
  if (!codeAnswer.value.trim()) {
    ElMessage.warning('请输入代码')
    return
  }

  try {
    // 这里应该调用后端API来执行代码
    // 模拟代码执行
    codeOutput.value = '代码执行成功！'

    // 运行测试用例
    runTestCases()
  } catch (error) {
    codeOutput.value = `执行错误：${error.message}`
  }
}

const runTestCases = () => {
  if (!testCases[currentQuestion.value.id]) return

  testResults.value = testCases[currentQuestion.value.id].map(testCase => {
    try {
      // 这里应该调用后端API来执行测试用例
      // 模拟测试用例执行
      const actual = '模拟的输出结果'
      const passed = testCase.validate(actual)

      return {
        input: testCase.input,
        expected: testCase.expected,
        actual,
        passed,
        error: passed ? '' : '输出结果不符合预期'
      }
    } catch (error) {
      return {
        input: testCase.input,
        expected: testCase.expected,
        actual: '执行错误',
        passed: false,
        error: error.message
      }
    }
  })

  // 更新得分
  const passedTests = testResults.value.filter(result => result.passed).length
  score.value = (passedTests / testResults.value.length) * 100
}

const showTestCases = () => {
  showTestCasesDialog.value = true
}

// 笔记相关
const notes = ref([])
const showNoteDialog = ref(false)
const currentNote = ref(null)
const noteForm = ref({
  categoryId: '',
  content: ''
})

// 笔记分类相关
const categories = ref([
  { id: 1, name: '概念理解', color: 'success' },
  { id: 2, name: '代码示例', color: 'warning' },
  { id: 3, name: '问题记录', color: 'danger' },
  { id: 4, name: '心得体会', color: 'info' }
])

const selectedCategory = ref('')
const searchKeyword = ref('')

// 过滤后的笔记列表
const filteredNotes = computed(() => {
  let result = notes.value

  // 按分类筛选
  if (selectedCategory.value) {
    result = result.filter(note => note.categoryId === selectedCategory.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(note =>
      note.content.toLowerCase().includes(keyword) ||
      getCategoryName(note.categoryId).toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

// 获取分类标签类型
const getCategoryTagType = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.color : 'info'
}

// 导出笔记
const exportNotes = () => {
  const exportData = filteredNotes.value.map(note => ({
    '创建时间': formatTime(note.createTime),
    '分类': getCategoryName(note.categoryId),
    '内容': note.content
  }))

  const ws = XLSX.utils.json_to_sheet(exportData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '笔记')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '学习笔记.xlsx')
}

// 修改保存笔记方法
const saveNote = () => {
  if (!noteForm.value.content.trim()) {
    ElMessage.warning('笔记内容不能为空')
    return
  }

  if (currentNote.value) {
    // 编辑现有笔记
    currentNote.value.content = noteForm.value.content
    currentNote.value.categoryId = noteForm.value.categoryId
    currentNote.value.updateTime = Date.now()
  } else {
    // 添加新笔记
    notes.value.unshift({
      id: Date.now(),
      content: noteForm.value.content,
      categoryId: noteForm.value.categoryId,
      createTime: Date.now(),
      updateTime: Date.now()
    })
  }

  showNoteDialog.value = false
  ElMessage.success(currentNote.value ? '笔记已更新' : '笔记已添加')
}

// 修改编辑笔记方法
const editNote = (note) => {
  currentNote.value = note
  noteForm.value = {
    categoryId: note.categoryId,
    content: note.content
  }
  showNoteDialog.value = true
}

// 删除笔记
const deleteNote = async (note) => {
  try {
    await ElMessageBox.confirm('确定要删除这条笔记吗？', '提示', {
      type: 'warning'
    })
    const index = notes.value.findIndex(n => n.id === note.id)
    if (index !== -1) {
      notes.value.splice(index, 1)
      ElMessage.success('笔记已删除')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 显示添加笔记对话框
const showAddNoteDialog = () => {
  currentNote.value = null
  noteForm.value = {
    categoryId: '',
    content: ''
  }
  showNoteDialog.value = true
}

// AI聊天相关
const showAIChat = ref(false)
const chatMessages = ref([])
const userInput = ref('')
const isLoading = ref(false)

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }

  const userMessage = {
    role: 'user',
    content: userInput.value,
    timestamp: Date.now()
  }

  chatMessages.value.push(userMessage)
  userInput.value = ''
  isLoading.value = true

  try {
    // 这里应该调用后端API获取AI回复
    // 模拟AI回复
    await new Promise(resolve => setTimeout(resolve, 1000))
    const aiMessage = {
      role: 'assistant',
      content: '这是一个模拟的AI回复。实际使用时需要调用后端API。',
      timestamp: Date.now()
    }
    chatMessages.value.push(aiMessage)
  } catch (error) {
    ElMessage.error('获取AI回复失败')
  } finally {
    isLoading.value = false
  }

  // 滚动到底部
  await nextTick()
  const chatMessagesEl = document.querySelector('.chat-messages')
  if (chatMessagesEl) {
    chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight
  }
}

// 清空对话
const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话记录吗？', '提示', {
      type: 'warning'
    })
    chatMessages.value = []
  } catch (error) {
    // 用户取消操作
  }
}

// 格式化消息内容（支持markdown）
const formatMessage = (content) => {
  // 这里可以添加markdown解析逻辑
  return content
}

// 组件销毁时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

onMounted(() => {
  // 初始化视频播放器
  // 这里可以添加视频播放器的初始化逻辑
})

// 右键菜单相关
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const selectedText = ref('')

// 处理右键菜单
const handleContextMenu = (e) => {
  e.preventDefault()
  contextMenuPosition.value = {
    x: e.clientX,
    y: e.clientY
  }
  
  // 获取选中的文本
  const selection = window.getSelection()
  selectedText.value = selection.toString().trim()
  
  contextMenuVisible.value = true

  // 点击其他地方关闭菜单
  const closeMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', closeMenu)
  }
  document.addEventListener('click', closeMenu)
}

// 处理AI提问
const handleAIQuestion = () => {
  contextMenuVisible.value = false
  showAIChat.value = true
}

// 处理选中文本提问
const handleSelectedTextQuestion = () => {
  contextMenuVisible.value = false
  showAIChat.value = true
}
</script>

<style scoped>
.course-detail {
  padding: 20px;
}

.video-section {
  margin-bottom: 30px;
}

.video-player {
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.video-info {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.video-meta {
  display: flex;
  gap: 20px;
  color: #666;
  margin-top: 10px;
}

.practice-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.question-card {
  margin-top: 20px;
}

.question-content {
  margin-bottom: 20px;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.practice-complete {
  text-align: center;
  padding: 40px 0;
}

.code-editor {
  margin-top: 20px;
}

.code-actions {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.code-output {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.code-output pre {
  margin: 0;
  white-space: pre-wrap;
}

.test-results {
  margin-top: 20px;
}

.test-case {
  margin: 10px 0;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.test-case.passed {
  border-color: #67c23a;
  background: #f0f9eb;
}

.test-case.failed {
  border-color: #f56c6c;
  background: #fef0f0;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.test-details {
  font-size: 14px;
}

.test-details p {
  margin: 5px 0;
}

.notes-section {
  margin-top: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.notes-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.note-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.note-time {
  color: #909399;
  font-size: 14px;
}

.note-actions {
  display: flex;
  gap: 10px;
}

.note-content {
  line-height: 1.6;
  color: #303133;
}

.note-content :deep(p) {
  margin: 0;
}

.note-content :deep(img) {
  max-width: 100%;
  height: auto;
}

.notes-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.note-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-chat-section {
  margin: 20px 0;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chat-messages {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.user-message .message-content {
  background: #409eff;
  color: #fff;
}

.ai-message .message-content {
  background: #fff;
  border: 1px solid #dcdfe6;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: right;
}

.chat-input {
  margin-top: 20px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.ai-assistant-trigger {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 100;
}

.context-menu {
  position: fixed;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  z-index: 3000;
  min-width: 150px;
}

.context-menu-item {
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #606266;
}

.context-menu-item:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.context-menu-item .el-icon {
  font-size: 16px;
}
</style>
